package com.cskaoyan.service.impl;

import com.cskaoyan.mapper.*;
import com.cskaoyan.model.*;
import com.cskaoyan.model.System;
import com.cskaoyan.model.bo.WxGoodsListBO;
import com.cskaoyan.model.vo.*;
import com.cskaoyan.service.WxGoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author ：王李轶群
 * @description：TODO
 * @date ：5/9/22 4:06 PM
 */
@Service
public class WxGoodsServiceImpl implements WxGoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    GrouponMapper grouponMapper;
    @Autowired
    IssueMapper issueMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CollectMapper collectMapper;
    @Autowired
    FootprintMapper footprintMapper;

    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    @Autowired
    SystemMapper systemMapper;

    @Override
    public BaseRespVO<Integer> goodsCount() {
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        goodsExampleCriteria.andDeletedEqualTo(false);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        int size = goods.size();
        BaseRespVO<Integer> integerBaseRespVO = new BaseRespVO<>();
        integerBaseRespVO.setData(size);
        integerBaseRespVO.setErrno(0);
        integerBaseRespVO.setErrmsg("成功");
        return integerBaseRespVO;
    }

    @Override
    public BaseRespVO<WxGoodsCategoryVO> goodsCategory(Integer id) {
        Category parentCategory = categoryMapper.selectByPrimaryKey(id);
        if (parentCategory.getLevel().equals("L1")) {
            CategoryExample categoryExample = new CategoryExample();
            CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
            categoryExampleCriteria.andPidEqualTo(id);
            List<Category> brotherCategory = categoryMapper.selectByExample(categoryExample);
            Category currentCategory = brotherCategory.get(0);
            WxGoodsCategoryVO wxGoodsCategoryVO = new WxGoodsCategoryVO();
            wxGoodsCategoryVO.setBrotherCategory(brotherCategory);
            wxGoodsCategoryVO.setCurrentCategory(currentCategory);
            wxGoodsCategoryVO.setParentCategory(parentCategory);
            BaseRespVO<WxGoodsCategoryVO> wxGoodsCategoryVOBaseRespVO = new BaseRespVO<>();
            wxGoodsCategoryVOBaseRespVO.setData(wxGoodsCategoryVO);
            wxGoodsCategoryVOBaseRespVO.setErrmsg("成功");
            wxGoodsCategoryVOBaseRespVO.setErrno(0);
            return wxGoodsCategoryVOBaseRespVO;
        }
        Integer pid = parentCategory.getPid();
        Category pParentcategory = categoryMapper.selectByPrimaryKey(pid);
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
        categoryExampleCriteria.andPidEqualTo(pid);
        List<Category> brotherCategory = categoryMapper.selectByExample(categoryExample);

        WxGoodsCategoryVO wxGoodsCategoryVO = new WxGoodsCategoryVO();
        wxGoodsCategoryVO.setBrotherCategory(brotherCategory);
        wxGoodsCategoryVO.setCurrentCategory(parentCategory);
        wxGoodsCategoryVO.setParentCategory(pParentcategory);
        BaseRespVO<WxGoodsCategoryVO> wxGoodsCategoryVOBaseRespVO = new BaseRespVO<>();
        wxGoodsCategoryVOBaseRespVO.setData(wxGoodsCategoryVO);
        wxGoodsCategoryVOBaseRespVO.setErrmsg("成功");
        wxGoodsCategoryVOBaseRespVO.setErrno(0);
        return wxGoodsCategoryVOBaseRespVO;
    }

    @Override
    public BaseRespVO<WxGoodsListVO> goodsList(WxGoodsListBO wxGoodsListBO) {
        Integer categoryId = wxGoodsListBO.getCategoryId();
        if (categoryId != null && wxGoodsListBO.getKeyword() == null) {
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            Integer pid = category.getPid();
            CategoryExample categoryExample = new CategoryExample();
            CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
            categoryExampleCriteria.andDeletedEqualTo(false);
            categoryExampleCriteria.andPidEqualTo(pid);
            List<Category> filterCategoryList = categoryMapper.selectByExample(categoryExample);
            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
            goodsExampleCriteria.andCategoryIdEqualTo(categoryId);
            goodsExampleCriteria.andDeletedEqualTo(false);
            PageHelper.startPage(wxGoodsListBO.getPage(), wxGoodsListBO.getLimit());
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);
            int pages = goodsPageInfo.getPages();
            long total = goodsPageInfo.getTotal();
            WxGoodsListVO wxGoodsListVO = new WxGoodsListVO();
            wxGoodsListVO.setFilterCategoryList(filterCategoryList);
            wxGoodsListVO.setLimit(wxGoodsListBO.getLimit());
            wxGoodsListVO.setList(goods);
            wxGoodsListVO.setPage(wxGoodsListBO.getPage());
            wxGoodsListVO.setPages(pages);
            wxGoodsListVO.setTotal((int) total);
            BaseRespVO<WxGoodsListVO> wxGoodsListVOBaseRespVO = new BaseRespVO<>();
            wxGoodsListVOBaseRespVO.setErrno(0);
            wxGoodsListVOBaseRespVO.setErrmsg("成功");
            wxGoodsListVOBaseRespVO.setData(wxGoodsListVO);
            return wxGoodsListVOBaseRespVO;
        }
        Integer brandId = wxGoodsListBO.getBrandId();
        if (brandId != null) {
            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
            goodsExampleCriteria.andDeletedEqualTo(false);
            goodsExampleCriteria.andBrandIdEqualTo(brandId);
            PageHelper.startPage(wxGoodsListBO.getPage(), wxGoodsListBO.getLimit());
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);
            int pages = goodsPageInfo.getPages();
            long total = goodsPageInfo.getTotal();
            WxGoodsListVO wxGoodsListVO = new WxGoodsListVO();
            wxGoodsListVO.setTotal((int) total);
            wxGoodsListVO.setPages(pages);
            wxGoodsListVO.setPage(wxGoodsListBO.getPage());
            wxGoodsListVO.setList(goods);
            wxGoodsListVO.setLimit(wxGoodsListBO.getLimit());
            BaseRespVO<WxGoodsListVO> wxGoodsListVOBaseRespVO = new BaseRespVO<>();
            wxGoodsListVOBaseRespVO.setErrno(0);
            wxGoodsListVOBaseRespVO.setErrmsg("成功");
            wxGoodsListVOBaseRespVO.setData(wxGoodsListVO);
            return wxGoodsListVOBaseRespVO;
        }
        String keyword = wxGoodsListBO.getKeyword();
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setOrderByClause(wxGoodsListBO.getSort() + " " + wxGoodsListBO.getOrder());
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        goodsExampleCriteria.andNameLike("%" + keyword + "%");
        PageHelper.startPage(wxGoodsListBO.getPage(), wxGoodsListBO.getLimit());
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);
        long total = goodsPageInfo.getTotal();
        int pages = goodsPageInfo.getPages();
        LinkedList<Category> categories = new LinkedList<>();
        LinkedList<Integer> ids = new LinkedList<>();
        for (Goods good : goods) {
            Integer categoryId1 = good.getCategoryId();
            if (!ids.contains(categoryId1)) {
                Category category = categoryMapper.selectByPrimaryKey(categoryId1);
                categories.add(category);
                ids.add(categoryId1);
            }

        }
        WxGoodsListVO wxGoodsListVO = new WxGoodsListVO();
        wxGoodsListVO.setFilterCategoryList(categories);
        wxGoodsListVO.setLimit(wxGoodsListBO.getLimit());
        wxGoodsListVO.setList(goods);
        wxGoodsListVO.setPage(wxGoodsListBO.getPage());
        wxGoodsListVO.setPages(pages);
        wxGoodsListVO.setTotal((int) total);
        BaseRespVO<WxGoodsListVO> wxGoodsListVOBaseRespVO = new BaseRespVO<>();
        wxGoodsListVOBaseRespVO.setErrno(0);
        wxGoodsListVOBaseRespVO.setErrmsg("成功");
        wxGoodsListVOBaseRespVO.setData(wxGoodsListVO);


        //插入历史记录
        SearchHistory searchHistory = null;
        String username = null;
        try {
            searchHistory = new SearchHistory();
            Subject subject = SecurityUtils.getSubject();
            username = (String) subject.getPrincipals().getPrimaryPrincipal();
        } catch (Exception e) {
            return wxGoodsListVOBaseRespVO;
        }
        Integer userId = userMapper.selectUserId(username);
        searchHistory.setUserId(userId);
        searchHistory.setDeleted(false);
        Date date = new Date();
        searchHistory.setAddTime(date);
        searchHistory.setUpdateTime(date);
        searchHistory.setFrom("wx");
        searchHistory.setKeyword(keyword);
        searchHistoryMapper.insertSelective(searchHistory);
        return wxGoodsListVOBaseRespVO;
    }

    @Override
    public BaseRespVO<WxGoodsDetailVO> goodsDetail(Integer id) {
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        GoodsAttributeExample.Criteria goodsAttributeExampleCriteria = goodsAttributeExample.createCriteria();
        goodsAttributeExampleCriteria.andGoodsIdEqualTo(id);
        List<GoodsAttribute> attribute = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        Goods info = goodsMapper.selectByPrimaryKey(id);

        Integer brandId = info.getBrandId();
        Brand brand = brandMapper.selectByPrimaryKey(brandId);

        CommentExample commentExample = new CommentExample();
        CommentExample.Criteria commentExampleCriteria = commentExample.createCriteria();
        commentExampleCriteria.andTypeEqualTo((byte) 0);
        commentExampleCriteria.andValueIdEqualTo(id);
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        WxGoodsDetailCommentsVO comment = new WxGoodsDetailCommentsVO();
        comment.setCount(comments.size());
        comment.setData(comments);

        IssueExample issueExample = new IssueExample();
        List<Issue> issue = issueMapper.selectByExample(issueExample);

        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria goodsProductExampleCriteria = goodsProductExample.createCriteria();
        goodsProductExampleCriteria.andGoodsIdEqualTo(id);
        goodsProductExampleCriteria.andDeletedEqualTo(false);
        List<GoodsProduct> productList = goodsProductMapper.selectByExample(goodsProductExample);

        SystemExample systemExample = new SystemExample();
        SystemExample.Criteria criteria = systemExample.createCriteria();
        criteria.andKeyNameEqualTo("market_wx_share");
        List<System> systemValue = systemMapper.selectByExample(systemExample);
        String keyValue = systemValue.get(0).getKeyValue();
        Boolean share;
        if(keyValue.equals("false")){
            share = false;
        }else {
            share = true;
        }


        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        GoodsSpecificationExample.Criteria goodsSpecificationExampleCriteria = goodsSpecificationExample.createCriteria();
        goodsSpecificationExampleCriteria.andGoodsIdEqualTo(id);
        goodsSpecificationExampleCriteria.andDeletedEqualTo(false);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        LinkedList<WxGoodsDetailSpecificationVO> specificationList = new LinkedList<>();
        for (GoodsSpecification goodsSpecification : goodsSpecifications) {
            String specification = goodsSpecification.getSpecification();
            LinkedList<GoodsSpecification> goodsSpecifications1 = new LinkedList<>();
            goodsSpecifications1.add(goodsSpecification);
            WxGoodsDetailSpecificationVO wxGoodsDetailSpecificationVO = new WxGoodsDetailSpecificationVO();
            wxGoodsDetailSpecificationVO.setName(specification);
            wxGoodsDetailSpecificationVO.setValueList(goodsSpecifications1);
            specificationList.add(wxGoodsDetailSpecificationVO);
        }


        int userHasCollect = 0;

        try {

            Subject subject = SecurityUtils.getSubject();
            String username = (String) subject.getPrincipals().getPrimaryPrincipal();
            Integer userId = userMapper.selectUserId(username);
            CollectExample collectExample = new CollectExample();
            CollectExample.Criteria collectExampleCriteria = collectExample.createCriteria();
            collectExampleCriteria.andUserIdEqualTo(userId);
            collectExampleCriteria.andValueIdEqualTo(id);
            collectExampleCriteria.andTypeEqualTo((byte) 0);
            collectExampleCriteria.andDeletedEqualTo(false);
            List<Collect> collects = collectMapper.selectByExample(collectExample);
            if (collects.size() != 0) {
                userHasCollect = 1;
            }

            FootprintExample footprintExample = new FootprintExample();
            FootprintExample.Criteria footprintExampleCriteria = footprintExample.createCriteria();
            footprintExampleCriteria.andUserIdEqualTo(userId);
            footprintExampleCriteria.andGoodsIdEqualTo(id);
            footprintExampleCriteria.andDeletedEqualTo(false);
            List<Footprint> footprints = footprintMapper.selectByExample(footprintExample);
            if (footprints.size() == 0) {
                Footprint footprint = new Footprint();
                footprint.setDeleted(false);
                footprint.setAddTime(new Date());
                footprint.setUpdateTime(new Date());
                footprint.setGoodsId(id);
                footprint.setUserId(userId);
                footprintMapper.insert(footprint);
            } else {
                Footprint footprint = footprints.get(0);
                Integer footprintId = footprint.getId();
                Footprint footprint1 = new Footprint();
                footprint1.setId(footprintId);
                footprint1.setUpdateTime(new Date());
                footprintMapper.updateByPrimaryKeySelective(footprint1);
            }
        } catch (NullPointerException ex) {

        }


        WxGoodsDetailVO wxGoodsDetailVO = new WxGoodsDetailVO();
        wxGoodsDetailVO.setAttribute(attribute);
        wxGoodsDetailVO.setBrand(brand);
        wxGoodsDetailVO.setComment(comment);
        wxGoodsDetailVO.setInfo(info);
        wxGoodsDetailVO.setIssue(issue);
        wxGoodsDetailVO.setProductList(productList);
        wxGoodsDetailVO.setShare(share);
        wxGoodsDetailVO.setShareImage("");
        wxGoodsDetailVO.setGroupon(new Groupon[0]);
        wxGoodsDetailVO.setSpecificationList(specificationList);
        wxGoodsDetailVO.setUserHasCollect(userHasCollect);
        BaseRespVO<WxGoodsDetailVO> wxGoodsDetailVOBaseRespVO = new BaseRespVO<>();
        wxGoodsDetailVOBaseRespVO.setData(wxGoodsDetailVO);
        wxGoodsDetailVOBaseRespVO.setErrmsg("成功");
        wxGoodsDetailVOBaseRespVO.setErrno(0);


        return wxGoodsDetailVOBaseRespVO;


    }

    @Override
    public BaseRespVO<DataVO<Goods>> goodsRelated(Integer id) {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        Integer categoryId = goods.getCategoryId();
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        goodsExampleCriteria.andCategoryIdEqualTo(categoryId);
        goodsExampleCriteria.andDeletedEqualTo(false);
        PageHelper.startPage(1, 4);
        List<Goods> goods1 = goodsMapper.selectByExample(goodsExample);
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods1);
        long total = goodsPageInfo.getTotal();
        int pages = goodsPageInfo.getPages();
        DataVO<Goods> goodsDataVO = new DataVO<>();
        goodsDataVO.setLimit(4);
        goodsDataVO.setList(goods1);
        goodsDataVO.setPage(1);
        goodsDataVO.setPages(pages);
        goodsDataVO.setTotal((int) total);
        BaseRespVO<DataVO<Goods>> dataVOBaseRespVO = new BaseRespVO<>();
        dataVOBaseRespVO.setErrno(0);
        dataVOBaseRespVO.setErrmsg("成功");
        dataVOBaseRespVO.setData(goodsDataVO);
        return dataVOBaseRespVO;
    }
}
